package com.sg.common.empty.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;

import com.sg.common.empty.core.EpUtil;
import com.sg.common.login.entity.Member;
import com.sg.common.login.entity.Org;
import com.sg.common.login.entity.Role;
import com.sg.common.login.service.OrgMemberService;
import com.sg.common.utils.CollUtil;
import com.sg.common.utils.Constant;

public class SessionUtil {

	public static String sessionMsg(OrgMemberService omService,
			HttpServletRequest request, String memberCode, Member member) {
		HttpSession session = request.getSession();
		String oranMcode = Constant.getSessionMemberCode(request);
		// 需要每次判断新code与原code是否一致，因为单点登录中存在在其他系统注销并登录另外人员的情况，此时需要把session中的相关数据在设置一次
		// 不一致即为再次登陆，需重定义session数据
		if (!StringUtils.equals(oranMcode, memberCode)) {
			session.setAttribute(Constant.SESSION_MEMBER, member);
			session.setAttribute(Constant.SESSION_MEMBER_CODE, memberCode);
			String restaurantId = member.getRestaurantId();
			session.setAttribute(Constant.SESSION_MYRESTAURANT, restaurantId);
			// if(session.getAttribute(Constant.SESSION_MYORGS)==null){
//			List<Org> myOrgs = omService.findMyOrgs(member);
//			session.setAttribute(Constant.SESSION_MYORGS, myOrgs);
			// }
			// if(session.getAttribute(Constant.SESSION_MYORGS_INDIRECT)==null){
//			session.setAttribute(Constant.SESSION_MYORGS_INDIRECT,
//					omService.findMyOrgsIndirect(member));
			Org myDirectOrg = omService.findMyOffiOrg(member);
			if(myDirectOrg!=null){
				Org myDepOrg = omService.findParentOrgByLeve(myDirectOrg, 1);
				Org myWorkShopOrg = omService.findParentOrgByLeve(myDirectOrg, 2);
				session.setAttribute(Constant.SESSION_MYDEPORG, myDepOrg);
				session.setAttribute(Constant.SESSION_MYWORKSHOPORG, myWorkShopOrg);
			}
			
			
//			session.setAttribute(Constant.SESSION_MYOFFIORG,myDirectOrg);

//			List<Org> myManageOrgs = omService.bsyManageOrgs(myOrgs);
//			session.setAttribute(Constant.SESSION_MANAGE_ORGS_BSY, myManageOrgs);
		}
		List<String> myRoles = (List<String>) session
				.getAttribute(Constant.SESSION_MYROLES_CODE);
		String res = "";
		if (!StringUtils.equals(oranMcode, memberCode) || CollUtil.isEmpty(myRoles)) {
			String yornsso = Constant.get("yornsso");
			if (yornsso.equals("yes")) {
				myRoles = EpUtil.findRemoteRoles(request, memberCode);
				if(myRoles!=null){
					session.setAttribute(Constant.SESSION_MYROLES_CODE, myRoles);
				}else{
					res = "error";
				}
				
			}else{
				//TODO
			}

		}
		return res;
	}
	
}
